﻿using System;
using System.Collections;
using System.Data.Linq.Mapping;
using System.Runtime.Serialization;
using Portal.Data.Helper;
using Portal.Core;
using Portal.Core.Binding.FormBuilder;
using Portal.Core.Helper;
using System.Linq;

namespace Portal.Data.Entity
{
    [Table(Name = "dbo.Option"), Serializable, DataContractAttribute]
    public class Option : BaseObject
    {
        #region Ctor
        public Option()
        {
        }

        public Option(int id, string fullName)
        {
            ID = id;
            FullName = fullName;
        }
        #endregion

        #region Properties
        public int ID { get { return Option_ID; } set { Option_ID = value; } }

        [SkipBinding]
        [Column(IsPrimaryKey = true, IsDbGenerated = true)]
        public int Option_ID { get; set; }

        [Column]
        public string FullName { get; set; }

        [Column,
         Lookup(DataSource = "ListAll", DisplayField = "Name", Type = typeof(ObjectTypeClass))]
        public int OptionType { get; set; }


        #endregion

        #region Methods
        public static Option FindByPrimaryKey(object objectid)
        {
            return FindByPrimaryKey<Option>(objectid);
        }
        public static IList FindByBook(int bookId)
        {
            if (bookId <= 0)
                return new ArrayList();

            //getcache  -----------------------
            var parameter = new object[] { typeof(Option).Name, "FindByBook", bookId };
            var obj = CacheHelper.Instance.Get(parameter);
            if (obj != null)
                return (IList)obj;
            //end get cache -------------------

            var sql = "select c.* from [Option] c INNER JOIN BookOption oc ON oc.Option_ID=c.Option_ID where oc.Book_ID={0}";
            sql += " order by oc.Sort";
            var result = LINQHelper.GetList<Option>(sql, bookId);
            CacheHelper.Instance.Set(parameter, result);
            return result;
        }
        public static IList ListAll()
        {
            //getcache  -----------------------
            var parameter = new object[] { typeof(Option).Name, "ListAll" };
            var obj = CacheHelper.Instance.Get(parameter);
            if (obj == null)
            {
                var result = LINQHelper.GetList<Option>("select * from [Option] order by FullName");
                CacheHelper.Instance.Set(parameter, result);
                return result;
            }
            return (IList)obj;
        }
        public static IList ListAllWithNone()
        {
            IList list = new ArrayList(ListAll());
            list.Insert(0, new Option(0,"--Không chọn--"));
            return list;
        }
        #endregion Methods

    }
}
